package vip.web3.admin.sys.controller.biz;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import vip.web3.admin.sys.controller.base.AbstractController;
import vip.web3.admin.sys.entity.biz.AProductEntity;
import vip.web3.admin.sys.form.user.ProductForm;
import vip.web3.admin.sys.form.user.ProductPageForm;
import vip.web3.admin.sys.mapper.AProductMapper;
import vip.web3.admin.sys.service.biz.IAProductService;
import vip.web3.common.exception.RRException;
import vip.web3.common.utils.PageUtils;
import vip.web3.common.utils.R;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * 轮次购买规则Controller
 *
 * aut-horlilei
 * @date 2024-09-27
 */
@RestController
@RequestMapping("/sys/product")
public class AProductController extends AbstractController {

    @Autowired
    private IAProductService aProductService;

    /**
     * 查询轮次购买规则列表
     */
    @RequiresPermissions("sys:product:list")
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params, @Valid ProductPageForm form) {
        PageUtils page = aProductService.pageProducts(params, form);
        return R.ok().put("page", page);
    }

    /**
     * 新增保存轮次购买规则
     */
    @RequiresPermissions("sys:product:add")
    @PostMapping("/add")
    public R addSave(@Valid @RequestBody ProductForm form) {
        AProductEntity entity = AProductMapper.INSTANCE.toAProductEntity(form);
        entity.setCreateDate(new Date());
        entity.setUpdateDate(new Date());
        aProductService.save(entity);
        return R.ok();
    }


    @GetMapping("/{id}")
    public R edit(@PathVariable("id") Integer id) {
        AProductEntity aProduct = aProductService.getById(id);
        return R.ok().put("data", aProduct);
    }

    /**
     * 修改保存轮次购买规则
     */
    @RequiresPermissions("sys:product:edit")
    @PostMapping("/edit")
    public R editSave(@Valid @RequestBody ProductForm form) {
        if(Objects.isNull(form)||form.getId()==null){
            throw new RRException("id为空!!", -1);
        }
        AProductEntity entity = AProductMapper.INSTANCE.toAProductEntity(form);
        entity.setUpdateDate(new Date());
        aProductService.updateById(entity);
        return R.ok();
    }

    /**
     * 删除轮次购买规则
     */
    @RequiresPermissions("sys:product:remove")
    @PostMapping("/remove")
    public R remove(@RequestBody Integer[] ids) {
        aProductService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }
}
